class SanPhamController < ApplicationController
  include ApplicationHelper
  def index
    redirect_url request.url
    @danh_muc = DanhMuc.find_by_slug(params[:danh_muc_slug]) || not_found
    @san_pham = SanPham.find_by_slug(params[:san_pham_slug]) 
    if @san_pham.danh_muc.id != @danh_muc.id 
      not_found
    end
    @ngon_ngu = I18n.locale.to_s
    @title = @san_pham.noi_dung(@ngon_ngu, true).tieu_de
    @san_pham_khacs = SanPham.where(:danh_muc_id => @danh_muc.id, :dang_kich_hoat => true).order("RANDOM()").limit(10).all
  end

  def nhom_san_pham
    redirect_url request.url
    @trang = (params[:page].present? && params[:page].to_i > 1 ?  params[:page] : 1).to_i
    @danh_muc = DanhMuc.find_by_slug(params[:danh_muc]) || not_found
    @ngon_ngu = I18n.locale.to_s
    @danh_muc_ngon_ngu = @danh_muc.danh_muc_ngon_ngus.select{ |v| v.ngon_ngu == @ngon_ngu }
    if (@danh_muc_ngon_ngu.empty?)
      @danh_muc_ngon_ngu = @danh_muc.danh_muc_ngon_ngus[0]
    else
      @danh_muc_ngon_ngu= @danh_muc_ngon_ngu[0]
    end
    
    @so_sp_moi_trang = CauHinh.gia_tri('san_pham_so_luong_tren_trang', 20).to_i

    query = SanPham.where(:danh_muc_id => @danh_muc.id, :dang_kich_hoat => true)

    @san_phams = query.paginate(
      :order => :gia.asc,
      :per_page => @so_sp_moi_trang,
      :page => @trang
    )
    @co_trang_sau = !query.paginate(
      :order => :gia.asc,
      :per_page => @so_sp_moi_trang,
      :page => @trang + 1
    ).empty?
    
    # @san_phams = @san_phams + @san_phams + @san_phams + @san_phams + @san_phams + @san_phams
    @co_trang_truoc = @trang > 1
    @index_dau_tien = (@trang - 1) * 20
    @title = @danh_muc_ngon_ngu.ten
  end
end
